<template>
	<view class="container999">
		<view class="isNavTop">
			<navTop :backgroundColor="true ? '#efefef' : '#efefef'" :needBorder="true ? false : true"
				:backColor="true ? 'black' : 'black'">
				<text style="font-weight: bold;color: black;">箭头挑战(小程序)</text>
			</navTop>
			<label v-if="!showBg" class="switch">
				<image :style="{'margin-top':statusBarHeight + 'px'}" @click.stop="toIndex"
					style="width: 50rpx;height: 50rpx;"
					src="https://mp-2dbd0ab2-e228-44f8-ad7a-fda8772e3c42.cdn.bspapp.com/bg/icon_index.png">
				</image>
			</label>
		</view>
		<view v-if="showBg" class="indexBox">
			<view @click="startOne" class="btn primary">开始挑战</view>
			<view style="margin-top: 100rpx;color: #9A9A9A;font-size: 24rpx;" v-if="userInfo && userInfo.scoreNum">
				<view class="scoreDesc">
					正确：{{userInfo.correctNum}}
					错误：{{userInfo.errorNum}}
					得分：{{userInfo.scoreNum}}
				</view>
				<view>
					总人数：{{userInfo.allPeople}}
					排名：{{userInfo.rank + 1}}
				</view>
				<view>
					{{userInfo.des}}
				</view>
			</view>
		</view>
		<view v-if="!showBg" class="gameBox">
			<view :style="'height:calc(94rpx + ' + statusBarHeight + 'px)'"></view>
			<view v-if="nowType != 3"  class="isFirst">
				<view class="firstTitle isFirstBg">请记住</view>
				<view class="rememberBox isFirstBg">
					<image style="width: 200rpx;height: 200rpx;" :style="'transform: rotate(' + topImg.rotate + 'deg'"
						:src="'../../static/arrow_' + topImg.name + '.png'"></image>
				</view>
				<view @click="startTwo" v-if="nowType == 1" class="firstBtn gary">记住了</view>
				<view v-if="nowType == 2" class="secordContent">
					<view class="secordTitle">请选择前一个箭头</view>
					<view class="secordBox">
						<view @click="isCheck(item,index)" v-for="(item,index) in showBottomImgList" :key="index"
							class="secordItem">
							<image v-if="index == checkIndex && isCheckStatus == 2"  class="statusImg" src="../../static/fail.png"></image>
							<image v-if="index == checkIndex && isCheckStatus == 1"  class="statusImg" src="../../static/true.png"></image>
							<image :style="'transform: rotate(' + item.rotate + 'deg'"
								style="width: 200rpx;height: 200rpx;position: relative;z-index: 1;" :src="'../../static/arrow_' + item.name + '.png'">
							</image>
						</view>
					</view>
					<view v-if="startTime && nowTime" style="display: flex;align-items: center;justify-content: center;">
						正确：{{correctNum || 0}}
						错误：{{errorNum || 0}}
						倒计时：{{((startTime - nowTime) / 1000) | timeChinese}}
					</view>
				</view>
			</view>
			<view v-if="nowType == 3" style="display: flex;align-items: center;justify-content: center;flex-direction: column;width: 100vw;height: 70vh;" class="secordContent">
				<view class="finishTitle">挑战结束</view>
				<view>正确：{{correctNum || 0}} 错误：{{errorNum || 0}}</view>
				<view style="margin-top: 20rpx;display: flex;
				align-items: center;
				justify-content: center;">
					最终得分为{{correctNum - errorNum}}
					<text v-if="finishRes && finishRes.isNew" class="newLabel">新纪录</text>
				</view>
				
				<view style="margin-top: 100rpx;color: #9A9A9A;font-size: 24rpx;" v-if="finishRes">
					<view>
						总人数：{{finishRes.allPeople}}
						排名：{{finishRes.rank + 1}}
					</view>
					<view>
						{{finishRes.des}}
					</view>
				</view>
				
				<!-- <view>超越了100%的用户！</view> -->
				<view class="finishBtnBox">
					<view @click="toIndex" style="margin-right: 30rpx;" class="btn primary">回到主页</view>
					<view @click="startOne" class="btn gary">再次挑战</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	let innerAudioContext = null;
	export default {
		data() {
			return {
				finishRes:'',
				rightMusic:'https://mp-b080d824-d0b8-4846-a88c-8f47223073a4.cdn.bspapp.com/right.mp3',
				failMusic:'https://mp-b080d824-d0b8-4846-a88c-8f47223073a4.cdn.bspapp.com/fail.mp3',
				needImg: {
					name: '0_0',
					rotate: 0
				},
				topImg: {
					name: '0_0',
					rotate: 0
				},
				showBottomImgList: [],
				saveBottomImgList: [],
				nowType: 1,
				showBg: true,
				statusBarHeight: uni.getSystemInfoSync()['statusBarHeight'],
				title: 'Hello',
				isCheckStatus:0,
				checkIndex:0,
				correctNum:0,
				errorNum:0,
				startTime:'',
				nowTime:'',
				isTimer:'',
				userInfo:''
			}
		},
		async onLoad() {
			if (!uni.getStorageSync('openId')) {
				await this.getUserOpenId();
				this.getUserInfo();
			}
		},
		onShow() {
			if(uni.getStorageSync('openId')){
				this.getUserInfo();
			}
		},
		onReady() {
			this.startMusic();
		},
		methods: {
			async getUserInfo() {
				let isRes = await this.zwyRequest({
					name: 'getUserInfo',
					data: {
						name: 'allInfo',
						openId: uni.getStorageSync('openId')
					}
				});
				console.log('getUserInfo', isRes);
				this.userInfo = isRes.result;
				uni.setStorageSync('userInfo', this.userInfo);
			},
			startMusic(){
				innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = false;
				innerAudioContext.loop = false;
				innerAudioContext.src = this.rightMusic ||
					'https://mp-b080d824-d0b8-4846-a88c-8f47223073a4.cdn.bspapp.com/right.mp3';
				innerAudioContext.onPlay(() => {
					// console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});	
			},
			isCheck(item,index) {
				
				if(this.isCheckStatus != 0){
					return;
				}
				
				// console.log('item', item);
				// 检验点击的箭头和需要的箭头是否一致
				this.checkIndex = index;
				let clickName = `${item.name}_${item.rotate}`;
				let needName = `${this.needImg.name}_${this.needImg.rotate}`;
				
				// this.nowClickName = clickName;
				
				if (clickName == needName) {
					// uni.showToast({
					// 	title: '选择正确',
					// 	icon: 'none'
					// })
					this.correctNum++;
					
					innerAudioContext.src = this.rightMusic ||
						'https://mp-b080d824-d0b8-4846-a88c-8f47223073a4.cdn.bspapp.com/right.mp3';
					
					if (innerAudioContext) {
						innerAudioContext.play();
					} else {
						this.startMusic();
						innerAudioContext.play();
					}
					
					this.isCheckStatus = 1;
					
				} else {
					// 错误
					
					this.errorNum++;
					innerAudioContext.src = this.failMusic ||
						'https://mp-b080d824-d0b8-4846-a88c-8f47223073a4.cdn.bspapp.com/fail.mp3';
					if (innerAudioContext) {
						innerAudioContext.play();
					} else {
						this.startMusic();
						innerAudioContext.play();
					}
					this.isCheckStatus = 2;
					// uni.showToast({
					// 	title: '选择错误!',
					// 	icon: 'none'
					// })
					
				}
				setTimeout(()=>{
					this.isCheckStatus = 0;
					this.createList();
				},300)
			},
			async getUserOpenId() {
				let loginRes = await uni.login();
				console.log('loginRes', loginRes);
				let postData = {
					code: loginRes.code
				}
				if (loginRes.anonymousCode) {
					postData['anonymousCode'] = loginRes.anonymousCode;
				}
			
				if (this.inviteId) {
					postData['inviteId'] = this.inviteId;
				}
				let isRes = await uniCloud.callFunction({
					name: 'login',
					data: postData
				});
				console.log('isRes', isRes);
				if (isRes && isRes.result && isRes.result.openid) {
					uni.setStorageSync('openId', isRes.result.openid);
				}
			},
			toIndex() {
				clearInterval(this.isTimer);
				this.showBg = true;
				this.nowType = 1;
				console.log('回到首页')
			},
			startTwo() {
				console.log('记住了');
				// 随机出新的箭头列表和需要记住的箭头
				
				this.errorNum = 0;
				this.correctNum = 0;
				this.startTime = new Date().getTime() + 60 * 1000;
				clearInterval(this.isTimer);
				this.isTimer = setInterval(()=>{
					this.nowTime = new Date().getTime();
					
					if(this.nowTime > this.startTime){
						clearInterval(this.isTimer);
						// 挑战结束
						// uni.showModal({
						// 	title:`挑战结束！您的得分是:${this.correctNum - this.errorNum }分`,
						// 	showCancel:false
						// });
						// this.toIndex();
						this.nowType = 3;
						this.finish();
					}
				},1000)
				this.createList();
				this.nowType = 2;
			},
			async finish(){
				this.finishRes = '';
				let res = await this.zwyRequest({
					name: 'getUserInfo',
					data: {
						name: 'finish',
						correctNum:this.correctNum,
						errorNum:this.errorNum
					}
				});
				this.finishRes = res.result;
				this.getUserInfo();
			},
			createList() {
				
				this.needImg = this.topImg;
				// 将当前记住的箭头存起来
				
				this.showBottomImgList = JSON.parse(JSON.stringify(this.saveBottomImgList));
				// 将下一个选项展示出来。
				
				let rotateList = [0, 45, 90, 135, 180, 225, 270, 315];
				let arrowList = [0, 1, 2, 3, 4, 5];
				let colorList = [0, 1, 2];
				let showBottomImgList = [];

				for (let i = 0; i < 4; i++) {
					let rotateIndex = Math.floor(Math.random() * rotateList.length);
					let arrowIndex = Math.floor(Math.random() * arrowList.length);
					let colorIndex = Math.floor(Math.random() * colorList.length);
					showBottomImgList.push({
						name: `${arrowList[arrowIndex]}_${colorList[colorIndex]}`,
						rotate: `${rotateList[rotateIndex]}`
					})
				}
				this.saveBottomImgList = showBottomImgList;
				let topImgIndex = Math.floor(Math.random() * showBottomImgList.length);
				this.topImg = showBottomImgList[topImgIndex];
			},
			startOne() {
				this.showBg = false;
				this.nowType = 1;
				this.createList();
				console.log('开始挑战,生成箭头列表和上面需要记住的箭头')
			}
		}
	}
</script>

<style lang="scss">
	.indexBox{
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}
	.newLabel{
		    background-color: #fef0f0;
		    border-color: #fde2e2;
		    color: #f56c6c;
			font-size: 20rpx;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
			margin-left: 20rpx;
	}
	.finishBtnBox{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 100rpx;
	}
	.finishTitle{
		font-weight: bold;
		font-size: 60rpx;
		margin-bottom: 100rpx;
	}
	.statusImg{
		width: 100rpx;
		height: 100rpx;
		z-index: 99;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		margin: auto;
	}
	.secordTitle {
		text-align: center;
		margin-top: 20rpx;
	}

	.secordBox {
		width: 90vw;
		display: flex;
		margin: 50rpx auto;
		align-items: center;
		justify-content: space-around;
		flex-wrap: wrap;

		.secordItem {
			position: relative;
			margin-right: 50rpx;
			margin-bottom: 30rpx;
		}
	}

	.gary {
		background-color: #909399;
	}

	.firstBtn {
		position: relative;
		left: 0;
		right: 0;
		margin: 100rpx auto;
		color: white;
		width: 240rpx;
		height: 60rpx;
		font-size: 30rpx;
		border-radius: 10rpx;
		text-align: center;
		line-height: 60rpx;
	}

	.isFirstBg {
		background-color: #efefef;
	}

	.firstTitle {
		text-align: center;
		font-size: 34rpx;
	}

	.rememberBox {
		background: #efefef;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100vw;
		height: 400rpx;
	}

	.gameBox {
		top: 0;
		z-index: 1;
		position: absolute;
	}

	.switch {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		position: absolute;
		left: 20rpx;
		top: 0;
		bottom: 0;
		margin: auto;
		z-index: 999;
		width: 200rpx;
	}

	.isNavTop {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		z-index: 99;
	}

	.container999 {
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		height: 100vh;
	}

	.primary {
		background-color: #409eff;
		color: white;
	}

	.btn {
		color: white;
		width: 240rpx;
		height: 60rpx;
		border-radius: 10rpx;
		text-align: center;
		line-height: 60rpx;
	}
</style>